package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.util.QiniuUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;

/**
 * @author spt
 * @description 预约设置控制器
 * @date
 **/
@RestController
@RequestMapping("/ordersetting")
@Slf4j
@Api(tags = "后台预约设置接口")
public class OrderSettingController {

    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";
    private static final String DATA_FORMAT = "yyyy/MM/dd";
    @Autowired
    private OrderSettingService orderSettingService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;
    /**
     * 预约管理_上传文件
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) throws Exception {
        log.warn("[预约设置-上传]fileName:{},size:{}", excelFile.getOriginalFilename(), excelFile.getSize());//警告,上传的文件名和文件大小为多少
        //1.首先判断传进来的文件是否合法
        checkFile(excelFile);
        Workbook workbook = getWorkBook(excelFile);
        //3.创建一个list泛型为OrderSettings集合对象
        List<OrderSetting> orderSettingList = new ArrayList<>();
        //遍历工作簿取数据
        for (Sheet sheet : workbook) {
            //获取当前表  遍历表 拿行  遍历当前行  拿单元格
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                //获取每一行
                Row row = sheet.getRow(i);
                log.info("打印row:{}",row);
                OrderSetting orderSetting = parseOrderSetting(row);
                //加入预约集合对象
                orderSettingList.add(orderSetting);
            }
        }
        orderSettingService.addAll(orderSettingList);
        return new Result(true, "批量导入预约设置数据成功");
    }
    private OrderSetting parseOrderSetting(Row row) {
        Date date = null;
        Integer number = null;
        log.info("打印数据:{}",row.getCell(0).getDateCellValue());
        try {
            //解析每一行   拿到单元格数据进行解析
            //获取第一个单元格日期
            if(null != row.getCell(0)){
                //没有数据返回null
                date = row.getCell(0).getDateCellValue();
            }
            //获取第二个单元格最大预约数量
            if (null != row.getCell(1)){
                //如果没有数据返回null
                double numberValue = row.getCell(1).getNumericCellValue();
                //将double型转为int型
                number = Double.valueOf(numberValue).intValue();
            }
        } catch (IllegalStateException | NumberFormatException e) {
            log.error("", e);
            throw new BusinessRuntimeException(String.format("数据格式错误,%s 第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        // 判断是否缺少数据
        if (null == date || null == number) {
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        return new OrderSetting(date, number);
    }

    /**
     * 预约管理_上传文件
     *
     * @param excelFile 接受的文件
     * @return 全局返回成功与否bean
     * @throws IOException io异常
     */
    public static Workbook getWorkBook(MultipartFile excelFile) {
        Workbook workbook = null;
        try {
            //2.根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            //2.1 获取文件名
            String fileName = excelFile.getOriginalFilename();
            //2.2 创建Workbook工作薄对象,表示整个excel
            workbook = new XSSFWorkbook();
            //获取excel文件的io流
            InputStream is = excelFile.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if (fileName.endsWith(XLS)) {
                //2003 版
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith(XLSX)) {
                //2007及以上
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }
    //校验文件是否合法
    public static void checkFile(MultipartFile excelFile) throws Exception {
        //判断文件是否存在
        if (excelFile == null) {
            throw new FileNotFoundException("文件不存在!");
        }
        //获得文件名
        String fileName = excelFile.getOriginalFilename();
        //判断文件是否为 xls或者xlsx类型的
        if (!fileName.endsWith(XLS) && !fileName.endsWith(XLSX)){
            throw new IOException(fileName + "不是Excel文件");
        }
    }

    /**
     *
     * @param year
     * @param month
     * @return 展示预约数据
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSetting(String year,String month){
        List<Map<String,Object>> os = orderSettingService.select(year,month);

        return new Result(true,MessageConst.ACTION_SUCCESS,os);
    }

    /**
     *
     * @param orderSetting
     * @return 修改单格预约数据
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        orderSettingService.editNumber(orderSetting);
        return new Result(true,MessageConst.ACTION_SUCCESS);
    }
}
